<template>
  <div>
    <h1>病案首页登记</h1>
    <el-table :data="patientList" stripe border fit highlight-current-row>
      <el-table-column prop="id" label="挂号ID" width="80" />
      <el-table-column prop="realname" label="姓名" width="120" />
      <el-table-column prop="gender" label="性别" width="80">
        <template #default="scope">
          {{ scope.row.gender === 1 ? '男' : '女' }}
        </template>
      </el-table-column>
      <el-table-column prop="age" label="年龄" width="80" />
      <el-table-column label="操作" width="100">
        <template #default="scope">
          <el-button type="text" size="small" @click="selectPatient(scope.row)">选择</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog v-model="dialogVisible" title="病案首页登记" width="60%">
      <el-form :model="medicalRecord" label-width="120px">
        <el-form-item label="主诉" prop="readme">
          <el-input v-model="medicalRecord.readme" placeholder="请输入主诉" />
        </el-form-item>
        <el-form-item label="现病史" prop="present">
          <el-input v-model="medicalRecord.present" placeholder="请输入现病史" />
        </el-form-item>
        <el-form-item label="既往史" prop="history">
          <el-input v-model="medicalRecord.history" placeholder="请输入既往史" />
        </el-form-item>
        <el-form-item label="过敏史" prop="allergy">
          <el-input v-model="medicalRecord.allergy" placeholder="请输入过敏史" />
        </el-form-item>
        <el-form-item label="体格检查" prop="physique">
          <el-input v-model="medicalRecord.physique" placeholder="请输入体格检查" />
        </el-form-item>
        <el-form-item label="诊断疾病">
          <el-select v-model="selectedDiseases" multiple placeholder="请选择诊断疾病">
            <el-option 
              v-for="disease in diseaseList" 
              :key="disease.id" 
              :label="disease.diseasename" 
              :value="disease.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="诊断类型">
          <el-select v-model="medicalDiseases[0].diagnosetype" placeholder="请选择诊断类型">
            <el-option value="1" label="西医"></el-option>
            <el-option value="2" label="中医"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="诊断种类">
          <el-select v-model="medicalDiseases[0].diagnosecate" placeholder="请选择诊断种类">
            <el-option value="1" label="初诊"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveMedicalRecord('save')">暂存</el-button>
          <el-button type="primary" @click="saveMedicalRecord('submit')">提交</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 添加操作提示对话框 -->
    <el-dialog v-model="actionDialogVisible" title="操作成功" width="30%">
      <p>病案首页登记已完成，请选择下一步操作：</p>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="actionDialogVisible = false">继续登记其他患者</el-button>
          <el-button type="primary" @click="goToCheckApply">开具检查申请</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import service from '@/utils/request'
import { useRouter } from 'vue-router'

const router = useRouter()

// 待接诊患者列表
const patientList = ref([])
// 疾病列表
const diseaseList = ref([])
// 选中的患者
const selectedPatient = ref(null)
// 病历信息
const medicalRecord = ref({
  readme: '',
  present: '',
  registid: null,
  casestate: null,
  history: '',
  allergy: '',
  physique: ''
})
// 诊断信息
const medicalDiseases = ref([{
  diseaseid: null,
  diagnostype: 1,
  diagnosecate: 1
}])
// 选中的疾病ID列表
const selectedDiseases = ref([])
// 对话框显示状态
const dialogVisible = ref(false)
// 操作成功后的选择对话框
const actionDialogVisible = ref(false)
// 保存成功后的医疗记录ID
const savedMedicalRecordId = ref(null)

// 检查用户是否登录
const checkLogin = () => {
  const token = localStorage.getItem('token')
  const userType = localStorage.getItem('userType')
  
  if (!token || userType !== '3') {
    ElMessage.error('请使用医生账号登录')
    router.push('/login')
    return false
  }
  
  return true
}

// 加载患者列表
const loadPatientList = async () => {
  if (!checkLogin()) return
  
  try {
    const response = await service.get('/api/doctor/patients/pending')
    patientList.value = response
  } catch (error) {
    console.error('加载待接诊患者列表失败:', error)
    handleApiError(error)
  }
}

// 加载疾病列表
const loadDiseaseList = async () => {
  try {
    const response = await service.get('/api/disease/search')
    diseaseList.value = response
  } catch (error) {
    console.error('加载疾病列表失败:', error)
    ElMessage.error('加载疾病列表失败，请检查网络连接')
  }
}

// 处理API错误
const handleApiError = (error) => {
  if (error.response) {
    if (error.response.status === 401) {
      ElMessage.error('登录已过期，请重新登录')
      localStorage.clear()
      router.push('/login')
    } else if (error.response.status === 403) {
      ElMessage.error('没有权限访问该资源')
    } else {
      ElMessage.error(`服务器错误: ${error.response.status}`)
    }
  } else if (error.request) {
    ElMessage.error('没有收到服务器响应，请检查网络连接')
  } else {
    ElMessage.error(`发生错误: ${error.message}`)
  }
}

// 选择患者
const selectPatient = (patient) => {
  selectedPatient.value = patient
  medicalRecord.value.registid = patient.id
  dialogVisible.value = true
}

// 保存或提交病历
const saveMedicalRecord = async (action) => {
  if (selectedDiseases.value.length === 0) {
    ElMessage.error('至少需要选择一个诊断疾病')
    return
  }

  const diagnoses = selectedDiseases.value.map(diseaseId => ({
    diseaseid: diseaseId,
    diagnostype: medicalDiseases.value[0].diagnostype,
    diagnosecate: medicalDiseases.value[0].diagnosecate
  }))

  try {
    const response = await service.post('/api/medical-record/save', {
      medicalRecord: medicalRecord.value,
      diagnoses: diagnoses,
      action: action
    })

    if (response.success) {
      ElMessage.success(response.message)
      
      // 保存医疗记录ID（如果后端返回了的话）
      if (response.medicalRecordId) {
        savedMedicalRecordId.value = response.medicalRecordId
      }
      
      // 将患者信息保存到sessionStorage，供检查申请页面使用
      const patientInfo = {
        caseNumber: selectedPatient.value.casenumber || selectedPatient.value.caseNumber,
        realName: selectedPatient.value.realname || selectedPatient.value.realName,
        gender: selectedPatient.value.gender,
        age: selectedPatient.value.age,
        ageType: selectedPatient.value.agetype || selectedPatient.value.ageType || '岁',
        medicalRecordId: savedMedicalRecordId.value || response.medicalRecordId,
        registerId: selectedPatient.value.id,
        // 添加更多可能需要的字段
        idNumber: selectedPatient.value.idnumber || selectedPatient.value.idNumber,
        homeAddress: selectedPatient.value.homeaddress || selectedPatient.value.homeAddress
      }
      
      console.log('保存患者信息到sessionStorage:', patientInfo)
      sessionStorage.setItem('currentPatient', JSON.stringify(patientInfo))
      
      // 关闭当前对话框
      dialogVisible.value = false
      
      // 显示操作选择对话框
      actionDialogVisible.value = true
      
      // 刷新患者列表
      loadPatientList()
      
      // 重置表单
      resetForm()
      
    } else {
      ElMessage.error(response.message)
    }
  } catch (error) {
    console.error('保存病历失败:', error)
    handleApiError(error)
  }
}

// 跳转到检查申请页面
const goToCheckApply = () => {
  actionDialogVisible.value = false
  router.push('/check-apply')
}

// 重置表单
const resetForm = () => {
  medicalRecord.value = {
    readme: '',
    present: '',
    registid: null,
    casestate: null,
    history: '',
    allergy: '',
    physique: ''
  }
  selectedDiseases.value = []
  medicalDiseases.value = [{
    diseaseid: null,
    diagnostype: 1,
    diagnosecate: 1
  }]
  selectedPatient.value = null
  savedMedicalRecordId.value = null
}

onMounted(() => {
  if (checkLogin()) {
    loadPatientList()
    loadDiseaseList()
  }
})
</script>